package com.optitronics.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.optitronics.beans.Client;
import com.optitronics.beans.OrderItem;
import com.optitronics.util.OptitronicsConstants;

@RequestMapping("/clients")
@Controller
public class ClientsController {

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String show(@PathVariable("id") Integer id, Model model) {
		model.addAttribute("client", Client.findClient(id));
		model.addAttribute("itemId", id);
		model.addAttribute("orderItems", OrderItem.findClientOrderItems(id));

		return "clients/show";
	}

	@RequestMapping(value = "/clientInfo/{name}/{email}/{flag}")
	public String clientInfo(@PathVariable("name") String name, @PathVariable("email") String email, Model model) {

		Client client = Client.findClientByNameAndEmail(name, email);
		if (client != null) {
			model.addAttribute("client", client);
			model.addAttribute("orderItems", OrderItem.findClientOrderItems(client.getId()));
			return "clients/clientInfo";
		} else {
			model.addAttribute("message", "error.client.not.found");
			return "infoPageBasic";
		}
	}

	@RequestMapping(method = RequestMethod.GET)
	public String list(@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "size", required = false) Integer size, Model model) {
		if (page != null || size != null) {
			int sizeNo = size == null ? OptitronicsConstants.PAGE_SIZE : size.intValue();
			model.addAttribute("clients",
					Client.findClientsEntries(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));
			float nrOfPages = (float) Client.countClients() / sizeNo;
			model.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1
					: nrOfPages));
		} else {
			model.addAttribute("clients", Client.findAllClients());
		}
		return "clients/list";
	}

}
